package com.wang.back.controller;

import com.alibaba.fastjson2.JSONObject;
import com.wang.common.util.ConstatFinalUtil;
import com.wang.common.util.DateUtil;
import com.wang.common.util.PageInfoUtil;
import com.wang.controller.BaseController;
import com.wang.users.pojo.*;
import com.wang.users.service.AadminsService;
import com.wang.users.service.AroleService;
import jakarta.servlet.ServletException;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 放一些模块相关的功能;一般来说是一个模块一个Servlet
 * @author Zjx
 */
@Controller
@RequestMapping(value = "/back/UsersBack")
@Log4j2
public class UsersBackController extends BaseController {
    @Autowired
    private AroleService roleService;
    @Autowired
    private AadminsService adminsService;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    /**
     * 查询角色列表
     */
    @RequestMapping("/roleList")
    public String roleList(String currentPage, String pageSize,
                           String keyword, String status, String stDate, String edDate,
                           Model model) {
        log.info("==角色列表页面==");
        String path = "/back/users/roleList";
        log.info("==分页信息==当前页:{},每页条数:{}", currentPage, pageSize);

        /* 分页 */
        PageInfoUtil pageInfoUtil = new PageInfoUtil();
        /* 因为分页要的是整数
         * 从页面接收的参数有以下几种情况:
         * 不传,就是null
         * 传了,是非数字
         * 肯定是无法保存为数字的.
         * 使用try catch解决;
         * 因为PageInfoUtil创建的对象有默认值,做容错处理 */
        try {
            pageInfoUtil.setPageSize(Integer.parseInt(pageSize));
            pageInfoUtil.setCurrentPage(Integer.parseInt(currentPage));
        } catch (NumberFormatException e) {
        }
        /* 时间范围 */
        Date stDateObj = this.dateUtil.strToDate(stDate);
        Date edDateObj = this.dateUtil.strToDate(edDate);
        AroleQuery roleQuery = new AroleQuery();
        Arole entity = roleQuery.getEntity();
        if (StringUtils.isNotEmpty(status)) {
            try {
                entity.setStatus(Byte.parseByte(status));
            } catch (Exception e) {
            }
        }
        roleQuery.setPubTimeSt(stDateObj);
        roleQuery.setPubTimeEd(edDateObj);
        roleQuery.setKeyword(keyword);
        roleQuery.setOrderBy("idDesc");
        List<Arole> roleList = this.roleService.findList(pageInfoUtil, roleQuery);
        /* 要把service中的结果数据放到四大作用域中 */
        model.addAttribute("roleList", roleList);
        model.addAttribute("pageInfoUtil", pageInfoUtil);
        model.addAttribute(AroleQuery.KEYWORD_FINA, keyword);
        model.addAttribute("status", status);
        model.addAttribute("stDate", stDate);
        model.addAttribute("edDate", edDate);
        return path;
    }

    /**
     * 管理员批量操作
     *
     */
    @RequestMapping("/adminsBatch")
    public String adminsBatch(String[] idsArr, String status) throws ServletException, IOException {
        log.info("==adminsBatch==");
        String resultInfo = "";
        String info = "总条数:%s,成功条数:%s,失败条数:%s";
        /* 接受选择的复选框 */
        /* 接受选择的状态 */
        log.info("=idsArr===" + Arrays.toString(idsArr));
        if (idsArr != null) {
            /* 成功条数 */
            int succedCount = 0;
            /* 失败条数 */
            int failedCount = 0;
            for (int i = 0; i < idsArr.length; i++) {
                String id = idsArr[i];
                /* 现根据id查询管理员对象 */
                Aadmins admins = this.adminsService.getById(id);
                if (admins != null) {
                    admins.setStatus(Byte.valueOf(status));
                    /* 更新数据库 */
                    boolean dbRes = this.adminsService.updateById(admins);
                    if (dbRes) {
                        /* 成功 */
                        succedCount++;
                    }
                } else {
                    failedCount++;
                }
            }
            resultInfo = String.format(info, idsArr.length, succedCount, failedCount);
        } else {
            resultInfo = "请勾选";
        }
        log.info(resultInfo);
        /* 要给相应 */
        return "redirect:/back/UsersBack/adminsList";
    }

    /**
     * 提交管理员重置密码
     *
     */
    @RequestMapping("/adminsUpdateResetPassSubmit")
    @ResponseBody
    public String adminsUpdateResetPassSubmit(String id, String password, Model model) {
        log.info("==adminsUpdateSubmit==");
        /* new对象 */
        Aadmins admins = this.adminsService.getById(id);
        model.addAttribute("admins", admins);
        /* 赋值 */
        admins.setPassword(password);
        /* 调用Service的方法入库 */
        boolean dbRes = this.adminsService.updateById(admins);
        /* 处理json */
        JSONObject resultJson = this.proccedResponseJson(dbRes);
        return resultJson.toJSONString();
    }

    /**
     * 打开管理员重置密码
     * @param id id
     * @param model model
     */
    @RequestMapping("/adminsUpdateResetPass")
    public String adminsUpdateResetPass(int id, Model model) throws ServletException, IOException {
        log.info("==adminsUpdate==");
        String path = "/back/users/adminsUpdateResetPass";
        Aadmins admins = this.adminsService.getById(id);
        model.addAttribute("admins", admins);
        return path;
    }

    /**
     * 用户在管理员添加页面录入信息后,点击提交
     *
     */
    @RequestMapping(value = "/adminsUpdateSubmit", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String adminsUpdateSubmit(Aadmins adminsReq,
                                     MultipartFile photoFile,
                                     Model model) throws IOException {
        log.info("==adminsUpdateSubmit==");
        /* new对象 */
        Aadmins admins = this.adminsService.getById(adminsReq.getId());
        model.addAttribute("admins", admins);
        /* 赋值 */
        admins.setRoleId(adminsReq.getRoleId());
        admins.setEmail(adminsReq.getEmail());
        admins.setNickName(adminsReq.getNickName());
        admins.setTrueName(adminsReq.getTrueName());
        admins.setPhone(adminsReq.getPhone());
        admins.setQq(adminsReq.getQq());
        admins.setWeChat(adminsReq.getWeChat());
        admins.setStatus(adminsReq.getStatus());

        /* 只有传图片才更新 */
        if (Objects.nonNull(photoFile)) {
            /* 处理文件
             * 网络路径
             * 真实路径
             * 相对路径:/uploadfiles/日期/uuid.png
             *  */
            String souRelaPath = admins.getPhotoPath();
            String truePath = ConstatFinalUtil.SYS_CONFIG_JSON.getString(ConstatFinalUtil.INFO_TRUEPATH);
            String relaPath = ConstatFinalUtil.SYS_CONFIG_JSON.getString(ConstatFinalUtil.INFO_RELAPATH);
            String fileName = photoFile.getOriginalFilename();
            relaPath = relaPath + "/" + this.dateUtil.dateToStr(new Date(), DateUtil.DATE_FORMAT) + "/" +
                    UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
            File trueFile = new File(truePath + relaPath);
            log.info("文件路径:{}", trueFile.getAbsolutePath());
            if (!trueFile.getParentFile().exists()) {
                /* 创建父目录 */
                trueFile.getParentFile().mkdirs();
            }
            photoFile.transferTo(trueFile);

            admins.setPhotoPath(relaPath);

            File oldFile = new File(truePath + souRelaPath);
            if (oldFile.exists()) {
                oldFile.delete();
                log.info("原文件删除成功:{}", oldFile.getAbsolutePath());
            }
        }
        /* 调用Service的方法入库 */
        boolean dbFlag = this.adminsService.updateById(admins);
        JSONObject resultJson = this.proccedResponseJson(dbFlag);
        /* 返回json给客户端 */
        return resultJson.toJSONString();
    }

    /**
     * 打开管理员更新页面
     *
     */
    @RequestMapping("/adminsUpdate")
    public String adminsUpdate(int id, String operType, Model model) throws ServletException, IOException {
        log.info("==adminsUpdate==");
        String path = "/back/users/adminsInfo";
        Aadmins admins = this.adminsService.getById(id);
        model.addAttribute("admins", admins);

        String operTypeUpdateInfo = "updateInfo";
        /* 接受一个参数 */
        if (operTypeUpdateInfo.equalsIgnoreCase(operType)) {
            /* 查询所有的角色 */
            AroleQuery roleQuery = new AroleQuery();
            Arole entity = roleQuery.getEntity();
            entity.setStatus(AroleEnum.STATUS_ENABLE.getCode());

            List<Arole> roleList = this.roleService.findList(roleQuery);
            model.addAttribute("roleList", roleList);
            path = "/back/users/adminsUpdate";
        }
        return path;
    }

    /**
     * 用户在管理员添加页面录入信息后,点击提交
     *
     */
    @RequestMapping(value = "/adminsInsertSubmit", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String adminsInsertSubmit(Aadmins admins) throws Exception {
        log.info("==adminsInsertSubmit==");
        /* 调用Service的方法入库 */
        boolean dbRes = this.adminsService.save(admins);
        /* 返回json给客户端 */
        JSONObject resultJson = this.proccedResponseJson(dbRes);
        return resultJson.toJSONString();
    }

    /**
     * 打开管理员添加页面
     *
     */
    @RequestMapping("/adminsInsert")
    public String adminsInsert(Model model) throws ServletException, IOException {
        log.info("==adminsInsert==");
        String path = "/back/users/adminsInsert";
        /* 查询所有的角色 */
        AroleQuery roleQuery = new AroleQuery();
        Arole entity = roleQuery.getEntity();
        entity.setStatus(AroleEnum.STATUS_ENABLE.getCode());

        List<Arole> roleList = this.roleService.findList(roleQuery);
        model.addAttribute("roleList", roleList);
        return path;
    }

    /**
     * 管理员列表页面
     *
     */
    @RequestMapping("/adminsList")
    public String adminsList(String currentPage, String pageSize,
                             String keyword, String status, String stDate, String edDate, String roleId,
                             Model model) throws ServletException, IOException {
        log.info("==管理员列表页面==");
        String path = "/back/users/adminsList";
        /* 从请求头中获取信息 */
        log.info("==分页信息==" + currentPage + "===" + pageSize);

        /* 分页 */
        PageInfoUtil pageInfoUtil = new PageInfoUtil();
        /* 因为分页要的是整数
         * 从页面接收的参数有以下几种情况:
         * 不传,就是null
         * 传了,是非数字
         * 肯定是无法保存为数字的.
         * 使用try catch解决;
         * 因为PageInfoUtil创建的对象有默认值,做容错处理 */
        try {
            pageInfoUtil.setPageSize(Integer.parseInt(pageSize));
            pageInfoUtil.setCurrentPage(Integer.parseInt(currentPage));
        } catch (NumberFormatException e) {
        }

        /* 从请求头中获取信息 */
        log.info("==搜索信息==" + keyword + "===" + status + "===" + stDate + "===" + edDate);
        /* 时间范围 */
        Date stDateObj = this.dateUtil.strToDate(stDate);
        Date edDateObj = this.dateUtil.strToDate(edDate);

        AadminsQuery adminsQuery = new AadminsQuery();
        Aadmins entity = adminsQuery.getEntity();
        if (StringUtils.isNotEmpty(status)) {
            try {
                entity.setStatus(Byte.parseByte(status));
            } catch (Exception e) {
            }
        }
        adminsQuery.setPubTimeSt(stDateObj);
        adminsQuery.setPubTimeEd(edDateObj);
        adminsQuery.setOrderBy("idDesc");
        /* 提交了一个线程 */
        this.taskExecutor.submit(() -> {
            log.info("==开启了一个线程=={}", Thread.currentThread());
            List<Aadmins> adminsList = this.adminsService.findList(pageInfoUtil, adminsQuery);
            /* 要把service中的结果数据放到四大作用域中 */
            model.addAttribute("adminsList", adminsList);
            return null;
        });

        model.addAttribute("pageInfoUtil", pageInfoUtil);
        model.addAttribute("keyword", keyword);
        model.addAttribute("status", status);
        model.addAttribute("roleId", roleId);
        model.addAttribute("stDate", stDate);
        model.addAttribute("edDate", edDate);

        /* 查询所有的角色 */
        AroleQuery roleQuery = new AroleQuery();
        Arole roleEntity = roleQuery.getEntity();
        roleEntity.setStatus(AroleEnum.STATUS_ENABLE.getCode());

        List<Arole> roleList = this.roleService.findList(roleQuery);
        model.addAttribute("roleList", roleList);
        return path;
    }
}
